package cn.mumzone.pos.ui.fragment;

import android.support.v4.widget.PopupWindowCompat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.mumzone.basic.base.BaseFragment;
import cn.mumzone.basic.util.AppDateUtil;
import cn.mumzone.basic.util.DisplayUtil;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.pos.R;
import cn.mumzone.pos.model.CardBalanceEntity;
import cn.mumzone.pos.model.DailyReportEntity;
import cn.mumzone.pos.model.DailySummaryEntity;
import cn.mumzone.pos.model.PayListEntity;
import cn.mumzone.pos.presenter.DailyReportPresenter;
import cn.mumzone.pos.presenter.contract.DailyReportContract;
import cn.mumzone.pos.ui.widgets.CardBalanceView;
import cn.mumzone.pos.ui.widgets.DailySummaryView;
import cn.mumzone.pos.ui.widgets.PaySummaryView;

/**
 * author:        yupeng
 * created on:    2019/7/11 14:13
 * description:   营业日报
 */
public class FRA_DailyNew extends BaseFragment<DailyReportPresenter> implements DailyReportContract.View {

    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.ll_time_select)
    LinearLayout llTimeSelect;
    @BindView(R.id.tv_print)
    TextView tvPrint;
    @BindView(R.id.tv_daily_amount_tip)
    TextView tvDailyAmountTip;
    @BindView(R.id.tv_daily_amount)
    TextView tvDailyAmount;
    @BindView(R.id.tv_daily_count_tip)
    TextView tvDailyCountTip;
    @BindView(R.id.tv_daily_count)
    TextView tvDailyCount;
    @BindView(R.id.tv_average_price_tip)
    TextView tvAveragePriceTip;
    @BindView(R.id.tv_average_price)
    TextView tvAveragePrice;
    @BindView(R.id.ll_daily_summary)
    LinearLayout llDailySummary;
    @BindView(R.id.tv_pay_list_tip)
    TextView tvPayListTip;
    @BindView(R.id.ll_pay_list)
    LinearLayout llPayList;
    @BindView(R.id.ll_card_summary)
    LinearLayout llCardSummary;

    public static FRA_DailyNew newInstance() {
        return new FRA_DailyNew();
    }

    private TextView tvPopText;
    private PopupWindow popupWindow;
    private TimePickerView datePickDialog;

    private String selectTimeStamp = "";

    @Override
    protected void initEventAndData() {
        initDatePickDialog();

        tvTime.setText(AppDateUtil.getDateToString(System.currentTimeMillis(), AppDateUtil.YYYY_MM_DD1));

        initPopView();

        selectTimeStamp = AppDateUtil.getDateToString(System.currentTimeMillis(),AppDateUtil.YYYY_MM_DD);

        mPresenter.requestDailyReportByDate(String.valueOf(selectTimeStamp));
    }

    @Override
    protected void onUserVisible() {
        mPresenter.requestDailyReportByDate(String.valueOf(selectTimeStamp));
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            mPresenter.requestDailyReportByDate(String.valueOf(selectTimeStamp));
        }
    }

    private void initDatePickDialog() {

        Calendar nowDate = Calendar.getInstance();
        int nowYear = nowDate.get(Calendar.YEAR);

        Calendar startDate = Calendar.getInstance();
        startDate.set(nowYear - 2, 0, 1);
        Calendar endDate = Calendar.getInstance();

        datePickDialog = new TimePickerBuilder(mContext, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                datePickDialog.dismiss();
                selectTimeStamp = AppDateUtil.getDateToString(date.getTime(),AppDateUtil.YYYY_MM_DD);
                mPresenter.requestDailyReportByDate(selectTimeStamp);
                tvTime.setText(AppDateUtil.getDateToString(date.getTime(), AppDateUtil.YYYY_MM_DD1));
            }
        }).isDialog(true).isCyclic(false).setOutSideCancelable(true)
                .setType(new boolean[]{true, true, true, false, false, false})
                .setDate(nowDate)
                .setRangDate(startDate, endDate)
                .build();
        datePickDialog.getDialog().getWindow().setLayout(DisplayUtil.dip2px(mContext, 500), WindowManager.LayoutParams.WRAP_CONTENT);
    }

    private void initPopView() {
        popupWindow = new PopupWindow(mContext);
        View view = LayoutInflater.from(mContext).inflate(R.layout.view_tip_pop, null);
        tvPopText = view.findViewById(R.id.tv_text);
        popupWindow.setWidth(DisplayUtil.dip2px(mContext, 220));
        popupWindow.setContentView(view);
        popupWindow.setOutsideTouchable(true);
    }

    @Override
    public void showDailyReport(DailyReportEntity entity, ArrayList<DailySummaryEntity> summaryList) {
        //营业额
        tvDailyAmount.setText(String.format("￥%s", StringUtils.getFormattedMoney(entity.getDailyAmount())));

        //客单数
        tvDailyCount.setText(StringUtils.getString(entity.getDailyCount()));

        //单均价
        tvAveragePrice.setText(String.format("￥%s", StringUtils.getFormattedMoney(entity.getAveragePrice())));


        initDailySummaryList(summaryList);

        initPaySummaryList(entity.getPayList());

        initCardBalanceList(entity.getOtherList());

        showLoadingDialog();

        llCardSummary.post(new Runnable() {
            @Override
            public void run() {
                dismissLoadingDialog();
            }
        });
    }

    private void initDailySummaryList(ArrayList<DailySummaryEntity> summaryList) {
        DailySummaryView.OnItemTipClickedListener listener = new DailySummaryView.OnItemTipClickedListener() {
            @Override
            public void onItemSelected(View view, String tip) {
                tvPopText.setText(tip);
                int offsetX = -DisplayUtil.dip2px(mContext, 220);
                int offsetY = -DisplayUtil.dip2px(mContext, 100) / 2 - DisplayUtil.dip2px(mContext, 50) / 2;
                PopupWindowCompat.showAsDropDown(popupWindow, view, offsetX, offsetY, Gravity.START);
            }
        };
        for (int index = 0; index < summaryList.size(); index++) {
            DailySummaryEntity summaryEntity = summaryList.get(index);
            DailySummaryView view;
            if (null == llDailySummary.getChildAt(index)) {
                view = new DailySummaryView(mContext);
                view.setOnItemTipClickedListener(listener);
                llDailySummary.addView(view);
            } else {
                view = (DailySummaryView) llDailySummary.getChildAt(index);
            }
            view.bindData(summaryEntity, index == summaryList.size() - 1);
        }
    }

    private void initPaySummaryList(List<PayListEntity> payList) {
        PaySummaryView titleView;
        if (null == llPayList.getChildAt(0)) {
            titleView = new PaySummaryView(mContext);
            llPayList.addView(titleView);
        }else {
            titleView = (PaySummaryView) llPayList.getChildAt(0);
        }
        titleView.bindData(null, false);

        for (int index = 0; index < payList.size(); index++) {
            PayListEntity payListEntity = payList.get(index);
            PaySummaryView view;
            if (null == llPayList.getChildAt(index + 1)) {
                view = new PaySummaryView(mContext);
                llPayList.addView(view);
            } else {
                view = (PaySummaryView) llPayList.getChildAt(index + 1);
            }
            view.bindData(payListEntity, index == payList.size() - 1);
        }
    }

    private void initCardBalanceList(List<CardBalanceEntity> otherList) {
        CardBalanceView titleView;
        if (null == llCardSummary.getChildAt(0)) {
            titleView = new CardBalanceView(mContext);
            llCardSummary.addView(titleView);
        }else {
            titleView = (CardBalanceView) llCardSummary.getChildAt(0);
        }
        titleView.bindData(null, false);

        for (int index = 0; index < otherList.size(); index++) {
            CardBalanceEntity balanceEntity = otherList.get(index);
            CardBalanceView view;
            if (null == llCardSummary.getChildAt(index + 1)) {
                view = new CardBalanceView(mContext);
                llCardSummary.addView(view);
            } else {
                view = (CardBalanceView) llCardSummary.getChildAt(index + 1);
            }
            view.bindData(balanceEntity, index == otherList.size() - 1);
        }
    }

    @OnClick({R.id.ll_time_select, R.id.tv_daily_amount_tip, R.id.tv_daily_count_tip, R.id.tv_average_price_tip, R.id.tv_pay_list_tip})
    void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_time_select:
                datePickDialog.show();
                break;
            case R.id.tv_daily_amount_tip:
                tvPopText.setText(R.string.sale_discount);
                popupWindow.showAsDropDown(view);
                break;
            case R.id.tv_daily_count_tip:
                tvPopText.setText(R.string.daily_count);
                popupWindow.showAsDropDown(view);
                break;
            case R.id.tv_average_price_tip:
                tvPopText.setText(R.string.average_price);
                popupWindow.showAsDropDown(view);
                break;
            case R.id.tv_pay_list_tip:
                tvPopText.setText(R.string.pay_list);
                popupWindow.showAsDropDown(view);
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (datePickDialog.isShowing()) {
            datePickDialog.dismiss();
        }
    }

    @Override
    protected int getLayout() {
        return R.layout.fra_daily_new;
    }
}
